//
//  MainEngine.m
//  TianyaQing
//
//  Created by gzty1 on 12-3-5.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "MainEngine.h"
#import "NoteInfo+YL8G.h"
#import "Instance.h"
#import "DialogUtil.h"
#import "tyconsts.h"
#import "RegexKitLite.h"
#import "UIDevice+IdentifierAddition.h"
#import "NSString+Code.h"
#import "JSON.h"
#import "Request.h"
#import "BaseResponseData.h"
#import "AppDelegate.h"
#import "UIColor+HTML.h"
#import "SkinManager.h"
#import "MobClick.h"

@interface MainEngine(private)
-(void)addNotifications;
-(void)removeNotifications;

- (NSString*)getAdRecomdKey;

@end

@implementation MainEngine

@synthesize mainViewController=mainViewController_;

-(id)initWithWindow:(UIWindow*)window;
{
    if(self=[super init])
	{
		//window
		window_=window;
        window_.backgroundColor=[UIColor blackColor];
        
        [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
        NSString* channel=(NSString*)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"channel"];
        [MobClick startWithAppkey:UMENG_APPKEY reportPolicy:(ReportPolicy) BATCH channelId:channel];
        
        UIColor* color=[UIColor colorWithHexString:@"f47920"];
        NSDictionary* dic=[NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"GeneralProperty" ofType:@"plist"] ];
        if(dic)
        {
            color=[UIColor colorWithHexString:(NSString*)[dic objectForKey:@"alertBgColorHex"]];
        }
        
        [DialogUtil initAlertCenterWithBgColor:color];
        [DialogUtil initWaitingView];
        
        [SkinManager instance];
        
        BOOL ret=[NoteInfo createMarkTableWithDatabase:INSTANCE.dataBase];
        NSLog(@"create table Mark:%@",(ret?@"success":@"fail"));
		//notifications
		[self addNotifications];
        
        ASIHTTPRequest* request=[Request statisticsStartCountWithDelegate:INSTANCE];
		request.tag=50;
        
        [INSTANCE.contextData importLoginInfo];
        BOOL autoLogin=[INSTANCE.contextData.userName length]>0;	
        if (autoLogin) 
        {
            NSString* username=INSTANCE.contextData.userName;
            NSString* password=INSTANCE.contextData.password;
            
            [Request loginWithUserName:username passWord:password delegate:self];
        }
        
        [self getControlData];
        
        int startCount=[GuideController startCount];
        if(startCount==0)
        {
            guideController_=[[GuideController alloc] init];
            NSArray* imageArray=imageArray=[NSArray arrayWithObject:[UIImage imageNamed:@"newcomer_guide.png"]];
            [guideController_ showGuideWithSuperView:window 
                                              bounds:window.bounds
                                             bgColor:[UIColor blackColor]
                                          imageArray:imageArray 
                                               index:0 
                                            delegate:self 
                                          buttonRect:CGRectMake(85, 390.5, 150, 35)
                                           closeRect:CGRectZero 
                                            animated:YES];           
        }
        else
        {
            mainViewController_=[[MainViewController alloc] init];
            //[window_ addSubview:mainViewController_.view];
            window_.rootViewController=mainViewController_;
        }
	}
	
	return self;
}

-(void)dealloc
{
    [guideController_ release];
	[self removeNotifications];
	[mainViewController_ release];
    [helpWebView_ release];
	[super dealloc];
}

-(void)addNotifications 
{

}

-(void)removeNotifications
{
	[NotificationCenter removeObserver:self];
}

- (NSString*)getAdRecomdKey
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* recomdKey = [defaults objectForKey:@"recomdKey"];
    if ([recomdKey length] > 0)
    {
        return recomdKey;
    }
    return AdRecomdKey;
}

#pragma mark -
#pragma mark ASIHTTPRequest
- (void)requestFinished:(ASIHTTPRequest *)request 
{
	NSLog(@"requestFinished \n %@",[request responseString]);
	BaseResponseData* data=[BaseResponseData responseDataWithRequest:request];
	BOOL success=[data success];
	if(success)
	{
		[[Instance instance].contextData parseDataDic:data.dataDic];

	}
}

- (void)requestFailed:(ASIHTTPRequest *)request 
{

}

#pragma mark - 控件代码
- (void)getControlData
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* lastTime = [defaults objectForKey:@"lastTime"];
    NSString* intervalDay = [defaults objectForKey:@"intervalDay"];
    if (lastTime ==nil || intervalDay==nil ||
        ([lastTime length] > 0 && [intervalDay length] > 0
            && [lastTime doubleValue]+[intervalDay intValue]*86400 < [[NSDate date] timeIntervalSince1970]))
    {
        NSLog(@"getControlData");
        helpWebView_ = [[UIWebView alloc] initWithFrame:CGRectZero];
        helpWebView_.delegate = self;
        NSMutableString* adUrl = [[NSMutableString alloc] init];
        NSString* ver=(NSString*)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        [adUrl appendFormat:@"%@?ver=%@&deviceID=%@", ControlAddress ,ver,[[UIDevice currentDevice]uniqueGlobalDeviceIdentifier]];
        NSURL *url = [NSURL URLWithString:adUrl]; 
        [adUrl release];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [helpWebView_ loadRequest:request];
    }
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView 
{
    NSString* html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
    NSString* regPublisherId = @"<meta http-equiv=\"publisherId\" content=\"(.*?)\">";
    NSString* publisherId = [html stringByMatching:regPublisherId capture:1];
    NSString* key = [publisherId doCipher:@"tianyaiphone and android" operation:kCCDecrypt];
    NSString* bodyText = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"];
    if ([publisherId length]>0 && [bodyText length]>0) 
    {
//        NSString* ss=@"{\"intervalDay\":\"1\",\"closeBaoku\":\"1\",\"showAd\":\"1\",\"appKey\":\"089dbe4f39034c469d57f731b071631c\"}";
//        NSString* encodess=[ss doCipher:key operation:kCCEncrypt];
        
        NSString* decode=[bodyText doCipher:key operation:kCCDecrypt];
        if ([decode length]>0)
        {
            SBJSON   *jsonParser = [SBJSON new];
            id idResponse = [jsonParser objectWithString:decode error:NULL];
            NSDictionary *resultDict = (NSDictionary *)idResponse;
            [jsonParser release];
            
            if (resultDict && [resultDict isKindOfClass:[NSDictionary class]])
            {
                NSString* intervalDay=[resultDict objectForKey:@"intervalDay"];
                NSString* closeBaoku=[resultDict objectForKey:@"closeBaoku"];
                NSString* showAd=[resultDict objectForKey:@"showAd"];
                NSString* appKey=[resultDict objectForKey:@"appKey"];
                NSString* regular=[resultDict objectForKey:@"regular"];
                NSString* recomdKey = [resultDict objectForKey:@"recomdKey"];
                NSString* closeRecommend=[resultDict objectForKey:@"closeRecommend"];
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                if ([intervalDay length]>0)
                {
                    [defaults setObject:intervalDay forKey:@"intervalDay"];
                }
                if ([closeBaoku length]>0)
                {
                    [defaults setObject:closeBaoku forKey:@"closeBaoku"];
                }
                if ([showAd length]>0)
                {
                    [defaults setObject:showAd forKey:@"showAd"];
                }
                if ([appKey length]>0)
                {
                    [defaults setObject:appKey forKey:@"appKey"];
                }
                if ([appKey length]>0)
                {
                    [defaults setObject:regular forKey:@"regular"];
                }
                
                
                if ([recomdKey length]>0)
                {
                    [defaults setObject:recomdKey forKey:@"recomdKey"];
                }
                
                if ([closeRecommend length]>0)
                {
                    [defaults setObject:closeRecommend forKey:@"closeRecommend"];
                }
                
                NSString* lastTime=[NSString stringWithFormat:@"%0.0f",[[NSDate date] timeIntervalSince1970]];
                [defaults setObject:lastTime forKey:@"lastTime"];
                [defaults synchronize];
            }
        }
    }
}

#pragma mark -
#pragma mark GuideControllerDelegate
-(void)handleGuideFinish
{
    [guideController_ hideGuideAnimated];
    
    mainViewController_=[[MainViewController alloc] init];
    //[window_ addSubview:mainViewController_.view];
    window_.rootViewController=mainViewController_;
}
-(void)handleGuidePageChanged:(GuideController*)guideController
{
    
}
@end
